package com.example.myweb.Service.Auth.Impl;

import com.example.myweb.Domain.Entity.User;

import com.example.myweb.Dto.AdminUserDetailDTO;
import com.example.myweb.Dto.FeedItemDTO;
import com.example.myweb.Dto.UserProfileDTO;
import com.example.myweb.Exception.CustomException;

import com.example.myweb.Repository.JpaRepository.FollowRepository;
import com.example.myweb.Repository.JpaRepository.UserRepository;
import com.example.myweb.Service.Auth.FeedService;
import com.example.myweb.Service.Auth.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private FeedService feedService; // 注入 FeedService 来复用逻辑
    @Autowired
    private FollowRepository followRepository; // 注入 FollowRepository 来检查关注状态

    @Override
    @Transactional(readOnly = true)
    public UserProfileDTO getUserProfile(Long profileUserId, Long currentUserId, Pageable pageable) {
        // 1. 获取主页用户信息
        User profileUser = userRepository.findById(profileUserId)
                .orElseThrow(() -> new CustomException("用户不存在", HttpStatus.NOT_FOUND));

        // 2. 获取该用户发布的内容列表
        Page<FeedItemDTO> contentPage = feedService.getUserFeed(profileUserId, pageable);

        // 3. 检查关注状态和是否是本人
        boolean isFollowing = false;
        boolean isMe = false;

        if (currentUserId != null) {
            if (currentUserId.equals(profileUserId)) {
                isMe = true;
            } else {
                // 如果查看者不是本人，则需要查询关注关系
                // 我们需要一个 User 对象来查询，所以先从DB获取当前用户
                User currentUser = userRepository.findById(currentUserId).orElse(null);
                if (currentUser != null) {
                    isFollowing = followRepository.findByFollowerAndFollowed(currentUser, profileUser).isPresent();
                }
            }
        }
        // === 新增：获取关注和粉丝数 ===
        Long followingCount = userRepository.countFollowingByUserId(profileUserId);
        Long followerCount = userRepository.countFollowersByUserId(profileUserId);


        // 4. 组装最终的 DTO
        UserProfileDTO profileDTO = new UserProfileDTO();
        profileDTO.setUserId(profileUser.getUserId());
        profileDTO.setNickname(profileUser.getNickname());
        profileDTO.setAvatarUrl(profileUser.getAvatarUrl());
        profileDTO.setBio(profileUser.getBio());
        profileDTO.setRegistrationTime(profileUser.getRegistrationTime());

        profileDTO.setIsFollowing(isFollowing);
        profileDTO.setIsMe(isMe);

        profileDTO.setContent(contentPage);
        profileDTO.setFollowingCount(followingCount);
        profileDTO.setFollowerCount(followerCount);
        profileDTO.setContent(contentPage);

        return profileDTO;
    }
    @Override
    @Transactional(readOnly = true)
    public Page<AdminUserDetailDTO> getAllUsersForAdmin(Pageable pageable) {
        Page<User> userPage = userRepository.findAll(pageable);
        return userPage.map(this::convertToAdminDto);
    }

    @Override
    @Transactional
    public void updateUserStatusByAdmin(Long userId, String statusStr) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new CustomException("用户不存在", HttpStatus.NOT_FOUND));

        try {
            User.UserStatus status = User.UserStatus.valueOf(statusStr.toUpperCase());
            user.setStatus(status);
            userRepository.save(user);
        } catch (IllegalArgumentException e) {
            throw new CustomException("无效的用户状态: " + statusStr, HttpStatus.BAD_REQUEST);
        }
    }

    private AdminUserDetailDTO convertToAdminDto(User user) {
        AdminUserDetailDTO dto = new AdminUserDetailDTO();
        dto.setUserId(user.getUserId());
        dto.setNickname(user.getNickname());
        dto.setEmail(user.getEmail());
        // 将枚举状态转换为小写字符串返回，更通用
        dto.setStatus(user.getStatus().name().toLowerCase());
        dto.setRegistrationTime(user.getRegistrationTime());
        dto.setLastLoginTime(user.getLastLoginTime());
        return dto;
    }
}
